﻿using GersonFrame.ABFrame;
using GersonFrame.Tool;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEditor;
using UnityEngine;

namespace GersonFrame
{



    public class BuildApk : MonoBehaviour
    {
        public static string m_BuildPath = Application.dataPath + "/../BuildTarget";
        public static string m_AndroidPath = m_BuildPath + "/Android/";
        public static string m_IOSPath = m_BuildPath + "/IOS/";
        public static string m_WindowsPath = m_BuildPath + "/Windows/";

        [MenuItem("Tools/BuildAPK")]
        public static void BuildAPK()
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
            BuildReflashAB();
        }



        [MenuItem("MyTools/打包/更新AB")]
        public static void BuildReflashAB()
        {
            OpenStoryPanelPrefab();
            PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
            //打AB包
            BundleEditor.BuildAB();
            BuildAPKByNowAB();
        }

        [MenuItem("MyTools/AB/拷贝AB文件到工程")]
        public static void CopyABFilesToProject()
        {
            DeleteDir(Application.streamingAssetsPath + "/AssetBundles");
            string abPath = BundleEditor.AssetBundlePath + "/";
            string targetpath = Application.streamingAssetsPath + "/AssetBundles/";
            Copy(abPath, targetpath);
            AssetDatabase.Refresh();
        }
        static void OpenStoryPanelPrefab()
        {
            string path = ABFrameConfigGeter.Config.TimeLinePrefabPath;
            if (!string.IsNullOrEmpty(path))
            {
                AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path));
            }
            else
            {
                MyDebuger.LogWarning("未配置timeline预制体 请检查是否需要配置");
            }

        }



        [MenuItem("MyTools/打包/不更新AB")]
        private static void BuildAPKByNowAB()
        {
            OpenStoryPanelPrefab();
            CopyABFilesToProject();
            //hotupdate 写入版本信息 
            SaveVersion(PlayerSettings.bundleVersion, PlayerSettings.applicationIdentifier);

            string aPkName = PlayerSettings.productName;
            string apkFloder = "";
            string savepath = "";
            if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
            {
                apkFloder = m_AndroidPath;
                savepath = apkFloder + aPkName + EditorUserBuildSettings.activeBuildTarget + string.Format("_{0:yyyy_MM_dd_HH_mm}", DateTime.Now) + ".apk";
            }
            else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
            {
                apkFloder = m_IOSPath;
                //打出xcode工程
                savepath = apkFloder + aPkName + EditorUserBuildSettings.activeBuildTarget + string.Format("_{0:yyyy_MM_dd_HH_mm}", DateTime.Now);
            }
            else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.StandaloneWindows || EditorUserBuildSettings.activeBuildTarget == BuildTarget.StandaloneWindows64)
            {
                apkFloder = m_WindowsPath;
                savepath = apkFloder + aPkName + EditorUserBuildSettings.activeBuildTarget + string.Format("_{0:yyyy_MM_dd_HH_mm}/{1}.exe", DateTime.Now, aPkName);
            }
            ///打包
            BuildPipeline.BuildPlayer(FindEnableEitorScenes(), savepath, EditorUserBuildSettings.activeBuildTarget, BuildOptions.None);
            Application.OpenURL("file://" + apkFloder);
            BundleEditor.ClearABNamesAndProgress();
        }
        private static string[] FindEnableEitorScenes()
        {
            List<string> editorscenes = new List<string>();
            ///获取编辑器下面设置好的所以场景
            foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
            {
                if (!scene.enabled) continue;
                editorscenes.Add(scene.path);
            }
            return editorscenes.ToArray();
        }


        public static void Copy(string srcpath, string targetpath)
        {
            try
            {
                if (!Directory.Exists(targetpath))
                {
                    Directory.CreateDirectory(targetpath);
                }
                string srcdir = Path.Combine(targetpath, Path.GetFileName(srcpath));
                if (Directory.Exists(srcpath))
                    srcdir += Path.DirectorySeparatorChar;

                if (!Directory.Exists(srcdir))
                    Directory.CreateDirectory(srcdir);
                //获取所有文件名
                string[] files = Directory.GetFileSystemEntries(srcpath);

                foreach (string file in files)
                {
                    //是否为文件夹
                    if (Directory.Exists(file))
                    {
                        Copy(file, srcdir);
                    }
                    //为文件
                    else
                    {
                        File.Copy(file, srcdir + Path.GetFileName(file), true);
                    }
                }
            }
            catch (Exception e)
            {
                MyDebuger.LogError("无法复制：" + srcpath + " 到" + targetpath + " error:" + e);
            }
        }



        public static void DeleteDir(string srcPath)
        {
            try
            {
                DirectoryInfo dirinfo = new DirectoryInfo(srcPath);
                if (dirinfo.Exists)
                {
                    dirinfo.Delete(true);
                }
                /* FileSystemInfo[] fileinfo = dirinfo.GetFileSystemInfos();
                 foreach (FileSystemInfo info in fileinfo)
                 {
                     if (info is DirectoryInfo)
                     {
                         DirectoryInfo subdir = new DirectoryInfo(info.FullName);
                         subdir.Delete(true);
                     }
                     else
                     {
                         File.Delete(info.FullName);
                     }
                 }*/
            }
            catch (Exception e)
            {
                MyDebuger.LogError(string.Format(" 删除文件失败 {0} error {1}", srcPath, e.ToString()));
            }
        }

        /// <summary>
        /// 文件夹移动
        /// </summary>
        /// <param name="srcFolderPath"></param>
        /// <param name="destFolderPath"></param>
        public static void FolderMove(string srcFolderPath, string destFolderPath)
        {
            //检查目标目录是否以目标分隔符结束，如果不是则添加之
            if (destFolderPath[destFolderPath.Length - 1] != Path.DirectorySeparatorChar)
                destFolderPath += Path.DirectorySeparatorChar;

            //判断目标目录是否存在，如果不在则创建之
            if (!Directory.Exists(destFolderPath))
                Directory.CreateDirectory(destFolderPath);
            string[] fileList = Directory.GetFileSystemEntries(srcFolderPath);
            foreach (string file in fileList)
            {
                if (Directory.Exists(file))
                    FolderMove(file, destFolderPath + Path.GetFileName(file));
                else
                    File.Move(file, destFolderPath + Path.GetFileName(file));
            }
            Directory.Delete(srcFolderPath);
        }

        [MenuItem("Tools/测试Version写入")]
        public static void TVersion()
        {
            SaveVersion(PlayerSettings.bundleVersion, PlayerSettings.applicationIdentifier);
        }

        [MenuItem("Tools/测试Version读取")]
        public static void TReadVersion()
        {
            TextAsset vesiontex = Resources.Load<TextAsset>("Version");
            if (vesiontex == null)
            {
                Debug.LogError("未读取到本地版本");
                return;
            }
            HotUpdateVersionInfo versionInfo = null;
            using (MemoryStream stream = new MemoryStream(vesiontex.bytes))
            {
                BinaryFormatter bf = new BinaryFormatter();
                versionInfo = bf.Deserialize(stream) as HotUpdateVersionInfo;
            }
        }

        //写入版本号 包名
        static void SaveVersion(string version, string package)
        {
            string savePath = Application.dataPath + "/Resources/VersionJson.json";
            if (File.Exists(savePath))
            {
                File.Delete(savePath);
            }
            HotUpdateVersionInfo fileversionInfo = null;

            using (FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8))
                {
                    string jsonstr = sr.ReadToEnd();
                    fileversionInfo = JsonUtility.FromJson<HotUpdateVersionInfo>(jsonstr);
                }
            }
            if (fileversionInfo == null)
                fileversionInfo = new HotUpdateVersionInfo();
            fileversionInfo.PackageName = package;
            fileversionInfo.Version = version;
            //写入文件
            using (FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate))
            {
                using (StreamWriter st = new StreamWriter(fs, System.Text.Encoding.UTF8))
                {
                    string versionInfoStr = JsonUtility.ToJson(fileversionInfo);
                    st.Write(versionInfoStr);
                }
            }

            string bytepath = Application.dataPath + "/Resources/Version.bytes";
            FileStream fbs = new FileStream(bytepath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            //清空文件流
            fbs.Seek(0, SeekOrigin.Begin);
            fbs.SetLength(0);
            BinaryFormatter bfm = new BinaryFormatter();
            bfm.Serialize(fbs, fileversionInfo);
            fbs.Close();
            //刷新才会写入AB 包
            AssetDatabase.Refresh();
        }
    }
}